<template>
  <div class="am-u-sm-12 am-form">
    <el-select
      v-if="areaTeam"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      @change="handleAreaTeamIdChange"
      v-model="formData.areaTeamId"
      placeholder="请选择区域"
    >
      <el-option
        v-for="item in areaTeams"
        :key="item.areaTeamId"
        :label="item.name"
        :value="item.areaTeamId"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="busTeam"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      multiple
      :disabled="busTeams.length === 0"
      v-model="formData.busTeamIds"
      placeholder="请选择业务组"
    >
      <el-option
        v-for="item in busTeams"
        :key="item.busTeamId"
        :label="item.name"
        :value="item.busTeamId"
      >
      </el-option>
    </el-select>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="period"
    >
      <el-date-picker
        v-model="year"
        type="year"
        :clearable="false"
        :editable="false"
        placeholder="请选择年份"
      >
      </el-date-picker>
    </div>
    <el-select
      :disabled="periods.length === 0"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      multiple
      v-if="period"
      v-model="formData.periodIds"
      placeholder="请选择期数"
    >
      <el-option
        v-for="item in periods"
        :key="item.periodId"
        :label="item.periodName"
        :value="item.periodId"
      >
      </el-option>
    </el-select>
    <el-select
      :disabled="periods.length === 0"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      multiple
      v-if="allperiod"
      v-model="formData.periodIds"
      placeholder="请选择期数"
    >
      <el-option
        v-for="item in periods"
        :key="item.periodId"
        :label="item.periodName"
        :value="item.periodId"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="product"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.productId"
      placeholder="产品线名称"
    >
      <el-option
        v-for="item in products"
        :key="item.productId"
        :label="item.name"
        :value="item.productId"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="grade"
      @change="handleChange(arguments[0], 'gradeIds', grades,'value')"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      multiple
      v-model="formData.gradeIds"
      placeholder="请选择年级"
    >
      <el-option
        value="-1"
        label="全部"
      >全部</el-option>
      <el-option
        v-for="item in grades"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="subject && !mutiSubject"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.subjectId"
      placeholder="请选择科目"
    >
      <el-option
        v-for="item in subjects"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="subject && mutiSubject"
      @change="handleChange(arguments[0], 'subjectIds', subjects,'value')"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.subjectIds"
      multiple
      placeholder="请选择科目"
    >
      <el-option
        value="-1"
        label="全部"
      >全部</el-option>
      <el-option
        v-for="(item,index) in subjects"
        :key="item.value"
        :label="item.label"
        v-if="index != 0"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="classStatus"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.status"
      placeholder="请选择班级状态"
    >
      <el-option
        v-for="item in statuses"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="segment"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.segmentNo"
      placeholder="请选择段次"
    >
      <el-option
        v-for="item in segmentNos"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="startDate"
    >
      <el-date-picker
        v-model="formData.startDate"
        type="date"
        placeholder="开始日期"
      >
      </el-date-picker>
    </div>

    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="endDate"
    >
      <el-date-picker
        v-model="formData.endDate"
        type="date"
        placeholder="结束日期"
      >
      </el-date-picker>
    </div>

    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="time"
    >
      <el-date-picker
        v-model="formData.time"
        type="daterange"
        :placeholder="timePlaceholder"
      >
      </el-date-picker>
    </div>

    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="payTime"
    >
      <el-date-picker
        v-model="formData.payTime"
        type="daterange"
        placeholder="支付日期"
      >
      </el-date-picker>
    </div>

    <el-select
      v-if="needWithPeriod"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.needWithPeriod"
      placeholder="请选择"
    >
      <el-option
        label="只查本期"
        value="0"
      >
      </el-option>
      <el-option
        label="查询同期"
        value="1"
      >
      </el-option>
    </el-select>

    <el-select
      v-if="accessType"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.accessType"
      placeholder="职能"
    >
      <el-option
        label="班主任"
        value="1"
      >
      </el-option>
      <el-option
        label="外部班主任"
        value="2"
      >
      </el-option>
    </el-select>
    <el-select
      v-if="workStatus"
      size="small"
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-model="formData.workStatus"
      placeholder="是否在职"
    >
      <el-option
        label="在职"
        value="1"
      >
      </el-option>
      <el-option
        label="离职"
        value="0"
      >
      </el-option>
    </el-select>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="className"
    >
      <el-input
        v-model="formData.className"
        placeholder="班级名称"
      ></el-input>
    </div>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="classNo"
    >
      <el-input
        v-model="formData.classNo"
        placeholder="班级编号"
      ></el-input>
    </div>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="campusName"
    >
      <el-input
        v-model="formData.campusName"
        placeholder="校区名称"
      ></el-input>
    </div>
    <div
      class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group"
      v-if="teacherName"
    >
      <el-input
        v-model="formData.teacherName"
        :placeholder="teacherNamePlaceholder"
      ></el-input>
    </div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-form-group am-u-end">
      <button
        @click="handleSearch"
        type="button"
        class="btn-search am-btn am-btn-default am-btn-success"
      >
        <span class="am-icon-search"></span>查询
      </button>
      <button
        v-if="synchronize"
        @click="handleSynchronize"
        type="button"
        class="btn-search am-btn am-btn-default am-btn-success"
      >
        同步TMS数据
      </button>
      <button
        v-if="hasExport"
        @click="handleExport"
        type="button"
        class="btn-search am-btn am-btn-default am-btn-success"
      >
        <span class="am-icon-search"></span>导出
      </button>
      <button
        v-if="hasSet && hasPermission('setting')"
        @click="handleSet"
        type="button"
        class="btn-search am-btn am-btn-default am-btn-success"
      >
        <span class="am-icon-cog"></span>设置
      </button>
    </div>
  </div>
</template>

<script>
import io from '../../lib/io'
import storage from '../../lib/storage'
import moment from 'moment'
import util from '../../lib/util'
export default {
  data: function() {
    return {
      products: [],
      periods: [],
      statuses: [
        { label: '初始化', value: 0 },
        { label: '报名中', value: 1 },
        { label: '已作废', value: 2 },
        { label: '已结课', value: 3 }
      ],
      segmentNos: [
        { label: '请选择段次', value: '' },
        { label: '段次1', value: 1 },
        { label: '段次2', value: 2 },
        { label: '段次3', value: 3 },
        { label: '段次4', value: 4 },
        { label: '段次5', value: 5 },
        { label: '段次6', value: 6 },
        { label: '段次7', value: 7 },
        { label: '段次8', value: 8 }
      ],
      year: moment().format('YYYY'),
      formData: {
        areaTeamId: '',
        busTeamIds: [],
        startDate: '',
        endDate: '',
        gradeIds: [],
        periodIds: [],
        subjectId: '',
        productId: '',
        className: '',
        teacherName: '',
        campusName: '',
        status: '',
        segmentNo: '',
        needWithPeriod: '0',
        payTime: [],
        time: [],
        accessType: '',
        subjectIds: [],
        classNo: '',
        workStatus: '1'
      },
      loanOnlyOnce: true
    }
  },
  props: {
    synchronize: {
      type: Boolean,
      default: false
    },
    payTime: {
      type: Boolean,
      default: false
    },
    time: {
      type: Boolean,
      default: false
    },
    timePlaceholder: {
      type: String,
      default: ''
    },
    classStatus: {
      type: Boolean,
      default: false
    },
    needWithPeriod: {
      type: Boolean,
      default: false
    },
    segment: {
      type: Boolean,
      default: false
    },
    teacherNamePlaceholder: {
      type: String,
      default: '教师名称'
    },
    areaTeam: {
      type: Boolean,
      default: false
    },
    busTeam: {
      type: Boolean,
      default: false
    },
    busTeamElse: {
      type: Boolean,
      default: false
    },
    period: {
      type: Boolean,
      default: false
    },
    product: {
      type: Boolean,
      default: false
    },
    grade: {
      type: Boolean,
      default: false
    },
    subject: {
      type: Boolean,
      default: false
    },
    className: {
      type: Boolean,
      default: false
    },
    classNo: {
      type: Boolean,
      default: false
    },
    teacherName: {
      type: Boolean,
      default: false
    },
    campusName: {
      type: Boolean,
      default: false
    },
    startDate: {
      type: Boolean,
      default: false
    },
    endDate: {
      type: Boolean,
      default: false
    },
    defaultEndDate: {
      type: Boolean,
      default: false
    },
    needInitSearch: {
      type: Boolean,
      default: true
    },
    needGradeSearch: {
      type: Boolean,
      default: false
    },
    hasExport: {
      type: Boolean,
      default: false
    },
    hasSet: {
      type: Boolean,
      default: false
    },
    accessType: {
      type: Boolean,
      default: false
    },
    mutiSubject: {
      type: Boolean,
      default: false
    },
    allperiod: {
      type: Boolean,
      default: false
    },
    needAllPeriod: {
      type: Boolean,
      default: false
    },
    workStatus:{
      type: Boolean,
      default: false
    }
  },
  computed: {
    areaTeams: function() {
      return this.$root.config.areaTeams || []
    },
    busTeams: function() {
      return this.formData.areaTeamId
        ? this.$root.config.groupBusTeams[this.formData.areaTeamId] || []
        : []
    },
    grades() {
      return this.$root.config.grades.map(function(item) {
        return { value: item.gradeId, label: item.gradeName }
      })
    },
    subjects() {
      return [{ value: '', label: '全部科目' }].concat(
        this.$root.config.subjects.map(function(item) {
          return { value: item.subjectId, label: item.subjectName }
        })
      )
    }
  },
  created() {
    if (window.config.areaTeams) {
      this.formData.areaTeamId = window.config.areaTeams[0].areaTeamId
    }
    if (this.defaultEndDate) {
      this.formData.endDate = moment().format('YYYY-MM-DD')
    }
    this.cache = storage.getMultipleToolbar()
    console.log('1', this.cache)

    if (this.cache) {
      this.formData.areaTeamId =
        this.cache.areaTeamId || this.formData.areaTeamId
      this.year = this.cache.year || this.year
      this.formData.busTeamIds =
        this.cache.busTeamIds || this.formData.busTeamIds
      this.formData.periodIds = this.cache.periodIds || this.formData.periodIds
      this.formData.gradeIds = this.cache.gradeIds || this.formData.gradeIds
    }

    this.loadProductsList()
    this.loadPeriodByYear()
    this.periodListForAreaTeam()
  },
  watch: {
    year(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.loadPeriodByYear()
      }
    }
  },
  methods: {
    handleChange(val, param, list, alia) {
      alia = alia || 'value'
      if (val.length > 0 && val[val.length - 1] === '-1') {
        this.formData[param] = []
        if (param != 'subjectIds') {
          list.map(i => {
            this.formData[param].push(i[alia])
          })
        } else {
          //科目的第一项为‘全部科目’，为了统一其他筛选，先去掉统一再结构上加
          list.map((i, j) => {
            if (j != 0) {
              this.formData[param].push(i[alia])
            }
          })
        }
      }
    },
    handleAreaTeamIdChange() {
      this.loadPeriodByYear()
      this.periodListForAreaTeam()
      this.formData.busTeamIds = []
      this.formData.periodIds = []
    },
    handleSearch(e) {
      if (
        this.needGradeSearch &&
        this.grade &&
        this.formData.gradeIds.length === 0
      ) {
        this.$alert('请选择年级！')
        return
      }
      if (
        this.needAllPeriod &&
        this.allperiod &&
        this.formData.periodIds.length === 0
      ) {
        this.$alert('请选择期数！')
        return
      }
      storage.setMultipleToolbar(
        Object.assign(this.formData, { year: this.year })
      )
      this.$emit('search', e)
    },
    handleSynchronize(e) {
      this.$emit('synchronize', e)
    },
    handleExport(e) {
      if (
        this.needGradeSearch &&
        this.grade &&
        this.formData.gradeIds.length === 0
      ) {
        this.$alert('请选择年级！')
        return
      }
      if (
        this.needAllPeriod &&
        this.allperiod &&
        this.formData.periodIds.length === 0
      ) {
        this.$alert('请选择期数！')
        return
      }
      this.$emit('export', e)
    },
    handleSet(e) {
      if (this.hasSet && !this.formData.areaTeamId) {
        this.$alert('请选择区域！')
        return
      }
      this.$emit('setting', e)
    },
    periodListForAreaTeam() {
      if (this.allperiod) {
        io.post(
          io.apiAdminPeriodListForAreaTeam,
          {
            areaTeamId: this.formData.areaTeamId
          },
          ret => {
            if (ret.success) {
              this.periods = ret.data
              if (
                this.cache &&
                this.formData.areaTeamId === this.cache.areaTeamId &&
                this.year === this.cache.year
              ) {
                this.formData.periodIds = this.cache.periodIds
              } else {
                this.formData.periodIds = []
              }
            } else {
              this.periods = []
            }
            if (this.periods.length === 0) {
              this.$alert('当前没有设置期数')
            }
          }
        )
      }
    },
    filterPeriod() {
      return new Promise((resolve, reject) => {
        io.post(
          io.apiAdminPeriodListForAreaTeam,
          {
            areaTeamId: this.formData.areaTeamId
          },
          ret => {
            if (ret.success) {
              let temPeriods = []
              ret.data.forEach(item => {
                if (
                  item.periodName.indexOf(moment(this.year).format('YYYY')) > -1
                ) {
                  this.formData.periodIds.forEach(perioId => {
                    if (perioId === item.periodId) {
                      temPeriods.push(perioId)
                    }
                  })
                }
              })

              this.formData.periodIds = temPeriods
              resolve()
            }
          }
        )
      })
    },
    loadPeriodByYear: function() {
      var _this = this
      if (this.period) {
        io.post(
          io.periodByYearAndAreaTeamId,
          {
            areaTeamId: this.formData.areaTeamId,
            year: this.year ? moment(this.year).format('YYYY') : ''
          },
          ret => {
            if (ret.success) {
              if (
                _this.cache &&
                _this.formData.areaTeamId === _this.cache.areaTeamId &&
                _this.year === _this.cache.year
              ) {
                _this.formData.periodIds = _this.cache.periodIds
                if (_this.cache.periodIds.length > this.periods) {
                  this.filterPeriod()
                }
              } else {
                _this.formData.periodIds = []
              }
              _this.periods = ret.data

              if (_this.periods.length === 0) {
                _this.$alert('当前没有设置期数')
                // _this.formData.periodIds = [];
              }

              // 把url传来参数显示到表单，并且查询
              if (this.loanOnlyOnce) {
                this.loanOnlyOnce = false
                this.changeInitSearchStatus()
              }
              if (
                this.year &&
                moment(this.year).format('YYYY') == util.getHashParamVal('year')
              ) {
                this.formData = util.searchHashParam(this.formData)
              }

              if (_this.needInitSearch && _this.periods.length > 0) {
                _this.handleSearch()
              }
            } else {
              _this.$alert(ret.desc)
            }

            // this.changeInitSearchStatus();
          }
        )
      }
    },
    loadProductsList: function() {
      var _this = this
      if (this.product) {
        io.post(io.apiAdminBaseProductList, {}, function(ret) {
          if (ret.success) {
            _this.products = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      }
    },
    changeInitSearchStatus() {
      let year = util.getHashParamVal('year')
      if (year != undefined) {
        this.year = moment(year).format('YYYY')
      }
    }
  }
}
</script>

<style lang="less">
.am-form input[type='text'][readonly] {
  cursor: text;
  background-color: transparent;
}
</style>
